package com.freejava.myblog.services;

import com.freejava.myblog.pojo.MyArticle;
import com.freejava.myblog.pojo.MyUser;
import com.freejava.myblog.tools.ErrorEnum;
import com.freejava.myblog.tools.JsonResultObject;
import com.freejava.myblog.tools.LoginUser;
import com.freejava.myblog.tools.Md5Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

@Service
public class UserService {

    @Autowired
    MongoTemplate mongoTemplate;

    private final String tableName = "my_users";
    public MyUser findUserById(int id) {
        Query query = Query.query(Criteria.where("id").is(id));
        return mongoTemplate.findOne(query, MyUser.class);
    }

    /**
     * 注册
     *
     * @param myUser 传递的用户数据
     * @return JsonResultObject
     */
    public JsonResultObject register(MyUser myUser) {
        /*
        myUser对象中存储的是明文密码
        数据库中是一定不能存储明文密码的
        拿到密码之后做加密操作，把加密之后数据做入库
        加密：
        可逆加密：明文和密文可以互相转换
        不可逆加密：md5，可以用于密码加密
         */
        // md5加密算法对密码进行加密
        String password = Md5Utils.stringToMD5(myUser.getPassword());
        myUser.setPassword(password);
        long unixTime = System.currentTimeMillis() / 1000L;
        int nowUnixTime = (int) unixTime;
        // 设置注册时间
        myUser.setRegTime(nowUnixTime);

        boolean addResult = false;

        // 初始化Json返回对象
        JsonResultObject jsonResult = this.initJsonResultObject();

        // 向mongodb的my_user 的collection中添加一条用户注册信息
        MyUser obj = mongoTemplate.save(myUser);
        if (obj != null) {
            addResult = true;
        }
        if (addResult) {
            jsonResult.setMessage("新建用户成功");
        } else {
            jsonResult.setErrorMessage("创建用户失败，请稍后重试");
            jsonResult.setErrorCode("202323");
        }

        return jsonResult;

    }

    public JsonResultObject login(LoginUser loginUser) {
        JsonResultObject result = this.initJsonResultObject();
        ErrorEnum enum1 = ErrorEnum.valueOf(ErrorEnum.class, "PASSWORD_OR_USERNAME_WRONG");

        try {
            // md5处理密码
            String password = Md5Utils.stringToMD5(loginUser.getPassword());
            loginUser.setPassword(password);
            // @Select("SELECT id FROM my_users WHERE name=#{name} and password =#{password}")
            // 用于存储条件对象
            Query query = new Query();
            Criteria nameCriteria = Criteria.where("name").is(loginUser.getName());
            Criteria passwordCriteria = Criteria.where("password").is(loginUser.getPassword());

            query.addCriteria(nameCriteria);
            query.addCriteria(passwordCriteria);

            MyUser hasUser = mongoTemplate.findOne(query, MyUser.class);
            if (hasUser == null) {
                result.setErrorMessage("用户名或者密码错误");
                result.setErrorCode(enum1.getErrorCode());
                result.setErrorMessage(enum1.getErrorMsg());
            } else {
                Integer userId = hasUser.getId();
                // 创建一个MyUser对象
                MyUser currentUser = new MyUser();
                currentUser.setId(userId);
                currentUser.setPassword(password);
                currentUser.setName(loginUser.getName());
                result.setData(currentUser);
                result.setMessage("登录成功");
            }
        } catch (Exception e) {
            result.setCode("500");
            result.setErrorCode("100211");
            result.setErrorMessage(e.getMessage());
        }

        return result;
    }

    public JsonResultObject initJsonResultObject() {
        JsonResultObject result = new JsonResultObject();
        result.setCode("200");
        result.setMessage("");
        result.setErrorCode("");
        result.setErrorMessage("");
        return result;
    }

}
